package com.aric.springbootmusic.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtils {
    /**
     * java服务端获取http请求的ip地址(获取前端的ip地址信息)
     * @param request
     * @return
     */
    public static String getRequestRealIp(HttpServletRequest request){
        String ip=request.getHeader("X-Forwarded-For");
        if(ip!=null && !"".equals(ip)){
            String[] ips=ip.split(",");
            ip=ips[0];
        }
        if(ip==null){
            ip=request.getHeader("X-Real-IP");
        }
        if(ip==null){
            //获取ip ip = 127.0.0.1
            ip=request.getRemoteAddr();
            //获取用户 user = 1746049870065139713
            String user = request.getRemoteUser();
            //获取主机 host = 127.0.0.1
            String host = request.getRemoteHost();
            //获取端口号 port = 52560
            int port = request.getRemotePort();
        }
        return ip;
    }

    /**
     * 获取服务器端ip地址
     * @return
     * @throws UnknownHostException
     */
    public static String getResponseRealIp() throws UnknownHostException {
        InetAddress host = InetAddress.getLocalHost();
        return host.getHostAddress();
    }
}
